﻿using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace Library
{
    public class CompCollection : Collection<Component>
    {
        Screen parent;
        List<int> inDrawOrder = new List<int>();

        public CompCollection(Screen parent_)
        {
            parent = parent_;
        }

        protected override void InsertItem(int index, Component item)
        {
            if (item.Parent != null && item.Parent != parent)
                item.Parent.Components.Remove(item);

            item.Parent = parent;
            item.DrawOrderChanged += new ComponentDrawOrderChangedEventHandler(ComponentDrawOrderChangedEventHandler);
            base.InsertItem(index, item);
            UpdateDrawPosition(item);
        }

        void ComponentDrawOrderChangedEventHandler(object sender, ComponentDrawOrderChangedEventArgs e)
        {
            UpdateDrawPosition(e.Component);
        }
        void UpdateDrawPosition(Component Component)
        {
            int ord = Component.DrawOrder;
            int loc = Items.IndexOf(Component);

            if (inDrawOrder.Contains(loc))
                inDrawOrder.Remove(loc);
            int i = 0;

            if (ord > 0)
            {
                while (i < inDrawOrder.Count)
                    if (Items[inDrawOrder[i]].DrawOrder >= ord)
                    {
                        if (Items[inDrawOrder[i]].DrawOrder > ord)
                            i++;
                        break;
                    }
                    else
                        i++;
            }
            inDrawOrder.Insert(i, Items.IndexOf(Component));
        }

        public ComponentEnumerator InDrawOrder
        {
            get { return new ComponentEnumerator(this, inDrawOrder); }
        }

        protected override void RemoveItem(int index)
        {
            Items[index].Parent = null;
            Items[index].DrawOrderChanged -= ComponentDrawOrderChangedEventHandler;

            base.RemoveItem(index);

            inDrawOrder.Clear();
            foreach (Component comp in Items)
                UpdateDrawPosition(comp);
        }
    }
}